﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;

namespace Fayshine.VA.Views.Reports
{
    public partial class MonthReports : Page
    {
        private bool m_IsFinshed1 = false;
        private bool m_IsFinshed2 = false;
        private StatisticsReportViewModel m_ViewModel;

        public MonthReports()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MonthReports_Loaded);
        }

        #region Event Methods

        private void MonthReports_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            cmbYear.ItemsSource = FayshineManager.Instance.GetYearSource();
            cmbMonth.ItemsSource = FayshineManager.Instance.GetMonthSource();
            cmbYear.SelectedValue = DateTime.Now.Year;
            cmbMonth.SelectedValue = DateTime.Now.Month;

            m_ViewModel = new StatisticsReportViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            m_ViewModel.AppendMultiHistoryPassenger += new AppendMultiHistoryPassengerEventHandler(m_ViewModel_AppendMultiHistoryPassenger);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        private void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                SetMonthInCountChart(firstHistoryPassengerFlow);
                SetMonthOutCountChart(firstHistoryPassengerFlow);
                SetStrandarChart(firstHistoryPassengerFlow);

                SetMonthWorkingDayChart();
                SetMonthHolidayChart();
                SetMonthWorkHolidayCompareChart();
                m_IsFinshed1 = true;
                ResetBusyIndicator();
            });
        }

        private void m_ViewModel_AppendMultiHistoryPassenger(string title, bool isIn, params List<HistoryPassengerFlow>[] historyPassengerFlows)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                var thisYearPassenger = historyPassengerFlows[0];
                var thisYearMonthPassenger = historyPassengerFlows[1];
                var lastYearPassenger = historyPassengerFlows[2];
                var lastYearMonthPassenger = historyPassengerFlows[3];
                var thisMonHistoryPassenger = historyPassengerFlows[4];

                //Set Year and Month Chart
                SetMonthCompareChart(thisYearPassenger, lastYearPassenger);
                SetThisYearMonthChart(thisYearPassenger, lastYearPassenger);
                SetMonthGateInOurCompareChart(thisMonHistoryPassenger);
                SetMonthGateProcentChart(thisMonHistoryPassenger);
                SetMonthDayChart(title, thisYearMonthPassenger, lastYearMonthPassenger);
                SetAllPassengerSexChart();
                SetPassengerAgeChart();
                m_IsFinshed2 = true;
                ResetBusyIndicator();
            });


        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcYearMonth != null)
                {
                    vcYearMonth.AxesX.Clear();
                    vcYearMonth.TrendLines.Clear();
                    vcYearMonth.Series.Clear();
                    vcYearMonth.Titles.Clear();
                }

                if (vcMonthCompare != null)
                {
                    vcMonthCompare.AxesX.Clear();
                    vcMonthCompare.TrendLines.Clear();
                    vcMonthCompare.Series.Clear();
                    vcMonthCompare.Titles.Clear();
                }

                if (vcGateCompare != null)
                {
                    vcGateCompare.AxesX.Clear();
                    vcGateCompare.TrendLines.Clear();
                    vcGateCompare.Series.Clear();
                    vcGateCompare.Titles.Clear();
                }

                if (vcGatePrecentCompare != null)
                {
                    vcGatePrecentCompare.AxesX.Clear();
                    vcGatePrecentCompare.TrendLines.Clear();
                    vcGatePrecentCompare.Series.Clear();
                    vcGatePrecentCompare.Titles.Clear();
                }

                if (vcGatePrecentCompare2 != null)
                {
                    vcGatePrecentCompare2.AxesX.Clear();
                    vcGatePrecentCompare2.TrendLines.Clear();
                    vcGatePrecentCompare2.Series.Clear();
                    vcGatePrecentCompare2.Titles.Clear();
                }

                if (vcMonthDayStatistics != null)
                {
                    vcMonthDayStatistics.AxesX.Clear();
                    vcMonthDayStatistics.TrendLines.Clear();
                    vcMonthDayStatistics.Series.Clear();
                    vcMonthDayStatistics.Titles.Clear();
                }

                if (vcMonthInCount != null)
                {
                    vcMonthInCount.AxesX.Clear();
                    vcMonthInCount.TrendLines.Clear();
                    vcMonthInCount.Series.Clear();
                    vcMonthInCount.Titles.Clear();
                }

                if (vcMonthOutCount != null)
                {
                    vcMonthOutCount.AxesX.Clear();
                    vcMonthOutCount.TrendLines.Clear();
                    vcMonthOutCount.Series.Clear();
                    vcMonthOutCount.Titles.Clear();
                }

                if (vcMonthStrandCount != null)
                {
                    vcMonthStrandCount.AxesX.Clear();
                    vcMonthStrandCount.TrendLines.Clear();
                    vcMonthStrandCount.Series.Clear();
                    vcMonthStrandCount.Titles.Clear();
                }

                if (vcMonthWorkDay != null)
                {
                    vcMonthWorkDay.AxesX.Clear();
                    vcMonthWorkDay.TrendLines.Clear();
                    vcMonthWorkDay.Series.Clear();
                    vcMonthWorkDay.Titles.Clear();
                }

                if (vcMonthHoliDay != null)
                {
                    vcMonthHoliDay.AxesX.Clear();
                    vcMonthHoliDay.TrendLines.Clear();
                    vcMonthHoliDay.Series.Clear();
                    vcMonthHoliDay.Titles.Clear();
                }

                if (vcMonthWorkHoliDay != null)
                {
                    vcMonthWorkHoliDay.AxesX.Clear();
                    vcMonthWorkHoliDay.TrendLines.Clear();
                    vcMonthWorkHoliDay.Series.Clear();
                    vcMonthWorkHoliDay.Titles.Clear();
                }

                if (vcThisMonthSex != null)
                {
                    vcThisMonthSex.AxesX.Clear();
                    vcThisMonthSex.TrendLines.Clear();
                    vcThisMonthSex.Series.Clear();
                    vcThisMonthSex.Titles.Clear();
                }
                if (vcLastMonthSex != null)
                {
                    vcLastMonthSex.AxesX.Clear();
                    vcLastMonthSex.TrendLines.Clear();
                    vcLastMonthSex.Series.Clear();
                    vcLastMonthSex.Titles.Clear();
                }
                if (vcLastYearSex != null)
                {
                    vcLastYearSex.AxesX.Clear();
                    vcLastYearSex.TrendLines.Clear();
                    vcLastYearSex.Series.Clear();
                    vcLastYearSex.Titles.Clear();
                }

                if (vcMonthAgeChart != null)
                {
                    vcMonthAgeChart.AxesX.Clear();
                    vcMonthAgeChart.TrendLines.Clear();
                    vcMonthAgeChart.Series.Clear();
                    vcMonthAgeChart.Titles.Clear();
                }

            });
        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                }
                else
                {
                    cbItemDisplay.Content = string.Empty;
                }
                cmbAreas.SelectedItem = null;
                cmbAreas.SelectedItem = cbItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string msg = string.Empty;
            
            m_ViewModel.UpdateCheckedAreas();

            if (!FayshineManager.Instance.ValidateAreaGateInputs(m_ViewModel.CheckedAreas,
                m_ViewModel.CheckedGates, ref msg))
            {
                MessageBox.Show(msg);
            }
            else
            {
                DateTime dateTime = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1);

                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                m_IsFinshed1 = false;
                m_IsFinshed2 = false;
                m_ViewModel.RefreshMonthReport(true, dateTime);
            }
        }

        #endregion

        #region Private Methods

        private void ResetBusyIndicator()
        {
            if (m_IsFinshed2 && m_IsFinshed1)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = false;
            }
        }

        private void SetMonthCompareChart(List<HistoryPassengerFlow> thisYearPassenger, List<HistoryPassengerFlow> lastYearPassenger)
        {
            DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1);
            List<HistoryPassengerFlow> sourcePassengers = new List<HistoryPassengerFlow>();
            
            HistoryPassengerFlow thisMonth = new HistoryPassengerFlow();
            thisMonth.DisplayTitle = "本月";
            thisMonth.AllInOut = thisYearPassenger.Where(t => t.HistoryTime.Month == time.Month).First().AllInOut;
            sourcePassengers.Add(thisMonth);

            HistoryPassengerFlow lastMonth = new HistoryPassengerFlow();
            lastMonth.DisplayTitle = "上月";
            if (time.Month == 1)
            {
                lastMonth.AllInOut = lastYearPassenger.Where(t => t.HistoryTime.Month == 12).First().AllInOut;
            }
            else
            {
                lastMonth.AllInOut = thisYearPassenger.Where(t => t.HistoryTime.Month == time.Month - 1).First().AllInOut;
            }
            sourcePassengers.Add(lastMonth);

            HistoryPassengerFlow lastYearMonth = new HistoryPassengerFlow();
            lastYearMonth.DisplayTitle = "去年同期";
            lastYearMonth.AllInOut = lastYearPassenger.Where(t => t.HistoryTime.Month == time.Month).First().AllInOut;
            sourcePassengers.Add(lastYearMonth);

            HistoryPassengerFlow thisYearAve = new HistoryPassengerFlow();
            thisYearAve.DisplayTitle = "今年平均";
            thisYearAve.AllInOut = Convert.ToInt32(thisYearPassenger.Average(t => t.AllInOut));
            sourcePassengers.Add(thisYearAve);

            HistoryPassengerFlow  lastYearAve = new HistoryPassengerFlow();
            lastYearAve.DisplayTitle = "去年平均";
            lastYearAve.AllInOut = Convert.ToInt32(lastYearPassenger.Average(t => t.AllInOut));
            sourcePassengers.Add(lastYearAve);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年" + time.Month + "月" + "同期客流对比";
            vcMonthCompare.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "本月", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = sourcePassengers;
            vcMonthCompare.Series.Add(series);

        }

        private void SetThisYearMonthChart(List<HistoryPassengerFlow> thisYearPassenger,List<HistoryPassengerFlow> lastYearPassenger)
        {
            DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1);
            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text =  time.Year+ "各月客流分布图";
            vcYearMonth.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "今年", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = thisYearPassenger;
            vcYearMonth.Series.Add(series);

            DataSeries series1 = ChartHelper.GetDataSeries(RenderAs.Column, "去年", ChartValueTypes.Auto);
            series1.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series1.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series1.DataSource = lastYearPassenger;
            vcYearMonth.Series.Add(series1);
        }

        private void SetMonthGateInOurCompareChart(List<HistoryPassengerFlow> thisHisoryPassengerFlows)
        {
            List<HistoryPassengerFlow> sources = thisHisoryPassengerFlows.OrderBy(o => o.DisplayTitle).ToList();

            DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1);
            string title1 = string.Empty;
            
            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name+" 各通道";
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年" + time.Month + "月" + title1 + " 进出客流对比";
            vcGateCompare.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "进", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            series.DataSource = sources;
            vcGateCompare.Series.Add(series);

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Column, "出", ChartValueTypes.Auto);
            series2.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            series2.DataSource = sources;
            vcGateCompare.Series.Add(series2);

        }

        private void SetMonthGateProcentChart(List<HistoryPassengerFlow> thisHistoryPassengerFlows)
        {
            List<HistoryPassengerFlow> sources = thisHistoryPassengerFlows.OrderBy(o => o.DisplayTitle).ToList();
            DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1);
            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name + " 各通道";
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年" + time.Month + "月" + title1 + " 进客流百分比";
            vcGatePrecentCompare.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Pie, "进", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            series.LabelText = "#AxisXLabel (#Percentage%)";
            series.DataSource = sources;
            vcGatePrecentCompare.Series.Add(series);

            Title vcChart1Title2 = new Visifire.Charts.Title();
            vcChart1Title2.Text = time.Year + "年" + time.Month + "月" + title1 + " 出客流百分比";
            vcGatePrecentCompare2.Titles.Add(vcChart1Title2);

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Pie, "出", ChartValueTypes.Auto);
            series2.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            series2.LabelText = "#AxisXLabel (#Percentage%)";
            series2.DataSource = sources;
            vcGatePrecentCompare2.Series.Add(series2);

        }

        private void SetMonthDayChart(string title,List<HistoryPassengerFlow> thisYearMonthPassenger, List<HistoryPassengerFlow> lastYearMonthPassenger)
        {
            DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1);
            time = time.AddMonths(1);
            int maxDay = time.AddDays(-1).Day;

            Axis xAxis = new Axis();
            xAxis.AxisMinimum = 0;
            xAxis.AxisMaximum = maxDay;
            xAxis.IntervalType = IntervalTypes.Auto;
            xAxis.Interval = 1;
            vcMonthDayStatistics.AxesX.Add(xAxis);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = title;
            vcMonthDayStatistics.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "本月", ChartValueTypes.Numeric);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "MonthOrDayOrWeek"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = thisYearMonthPassenger;
            vcMonthDayStatistics.Series.Add(series);

            DataSeries strandedSeries = ChartHelper.GetDataSeries(RenderAs.Line, "去年同期", ChartValueTypes.Numeric);
            strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "MonthOrDayOrWeek"));
            strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            strandedSeries.DataSource = lastYearMonthPassenger;
            vcMonthDayStatistics.Series.Add(strandedSeries);
        }

        private void SetMonthInCountChart(List<HistoryPassengerFlow> historyPassengerFlow)
        {
            Axis xAxis = new Axis();
            DateTime minDateTime = historyPassengerFlow.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = historyPassengerFlow.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            if (maxDateTime.Year == minDateTime.Year && maxDateTime.Month == minDateTime.Month &&
                maxDateTime.Day == minDateTime.Day)
            {
                xAxis.ValueFormatString = "HH:mm";
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 1;
            }
            else
            {
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 4;
            }
            vcMonthInCount.AxesX.Add(xAxis);

            int max = 0;
            double avg = 0;
            max = historyPassengerFlow.Select(s => s.InCount).Max();
            avg = historyPassengerFlow.Select(s => s.InCount).Average();

            DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1);
            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name + " 各通道";
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年" + time.Month + "月" + title1 + " 进客流分布图";
            vcMonthInCount.Titles.Add(vcChart1Title);

            TrendLine maxLine = new TrendLine();
            maxLine.Value = max;
            maxLine.LabelText = "最大:" + max.ToString();
            maxLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
            maxLine.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;

            TrendLine avgLine = new TrendLine();
            avgLine.Value = avg;
            avgLine.LabelText = "平均:" + Convert.ToInt32(avg).ToString();
            avgLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
            vcMonthInCount.TrendLines.Add(maxLine);
            vcMonthInCount.TrendLines.Add(avgLine);

            if (selectAreaExts.Count > 1)
            {
                selectAreaExts.each(s =>
                {
                    DataSeries tempSeries = ChartHelper.GetDataSeries(RenderAs.Line, s.Name, ChartValueTypes.Time);
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
                    tempSeries.DataSource = m_ViewModel.GetMonthPassengersByArea(time, s.ID);
                    vcMonthInCount.Series.Add(tempSeries);
                });
            }

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "所有店铺（和）", ChartValueTypes.Time);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            series.DataSource = historyPassengerFlow;
            vcMonthInCount.Series.Add(series);

        }

        private void SetMonthOutCountChart(List<HistoryPassengerFlow> historyPassengerFlow)
        {
            Axis xAxis = new Axis();
            DateTime minDateTime = historyPassengerFlow.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = historyPassengerFlow.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            if (maxDateTime.Year == minDateTime.Year && maxDateTime.Month == minDateTime.Month &&
                maxDateTime.Day == minDateTime.Day)
            {
                xAxis.ValueFormatString = "HH:mm";
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 1;
            }
            else
            {
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 4;
            }
            vcMonthOutCount.AxesX.Add(xAxis);

            int max = 0;
            double avg = 0;
            max = historyPassengerFlow.Select(s => s.OutCount).Max();
            avg = historyPassengerFlow.Select(s => s.OutCount).Average();

            DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1);
            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name + " 各通道";
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年" + time.Month + "月" + title1 + " 出客流分布图";
            vcMonthOutCount.Titles.Add(vcChart1Title);

            TrendLine maxLine = new TrendLine();
            maxLine.Value = max;
            maxLine.LabelText = "最大:" + max.ToString();
            maxLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
            maxLine.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;

            TrendLine avgLine = new TrendLine();
            avgLine.Value = avg;
            avgLine.LabelText = "平均:" + Convert.ToInt32(avg).ToString();
            avgLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
            vcMonthOutCount.TrendLines.Add(maxLine);
            vcMonthOutCount.TrendLines.Add(avgLine);

            if (selectAreaExts.Count > 1)
            {
                selectAreaExts.each(s =>
                {
                    DataSeries tempSeries = ChartHelper.GetDataSeries(RenderAs.Line, s.Name, ChartValueTypes.Time);
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
                    tempSeries.DataSource = m_ViewModel.GetMonthPassengersByArea(time, s.ID);
                    vcMonthOutCount.Series.Add(tempSeries);
                });
            }

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "进", ChartValueTypes.Time);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            series.DataSource = historyPassengerFlow;
            vcMonthOutCount.Series.Add(series);
        }

        private void SetStrandarChart(List<HistoryPassengerFlow> historyPassengerFlow)
        {
            Axis xAxis = new Axis();
            DateTime minDateTime = historyPassengerFlow.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = historyPassengerFlow.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            if (maxDateTime.Year == minDateTime.Year && maxDateTime.Month == minDateTime.Month &&
                maxDateTime.Day == minDateTime.Day)
            {
                xAxis.ValueFormatString = "HH:mm";
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 1;
            }
            else
            {
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 4;
            }
            vcMonthStrandCount.AxesX.Add(xAxis);

            DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1);
            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name + " 各通道";
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年" + time.Month + "月" + title1 + " 出客流分布图";
            vcMonthStrandCount.Titles.Add(vcChart1Title);

            //DataSeries accInSeries = ChartHelper.GetDataSeries(RenderAs.Area, "累计进", ChartValueTypes.Time);
            //accInSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            //accInSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AccumulateInCount"));
            //accInSeries.DataSource = historyPassengerFlow;

            //DataSeries accOutSeries = ChartHelper.GetDataSeries(RenderAs.Area, "累计出", ChartValueTypes.Time);
            //accOutSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            //accOutSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AccumulateOutCount"));
            //accOutSeries.DataSource = historyPassengerFlow;

            if (selectAreaExts.Count > 1)
            {
                selectAreaExts.each(s =>
                {
                    DataSeries tempSeries = ChartHelper.GetDataSeries(RenderAs.Line, s.Name, ChartValueTypes.Time);
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "StrandedCount"));
                    tempSeries.DataSource = m_ViewModel.GetMonthPassengersByArea(time, s.ID);
                    vcMonthStrandCount.Series.Add(tempSeries);
                });
            }

            DataSeries strandedSeries = ChartHelper.GetDataSeries(RenderAs.Line, "滞留人数", ChartValueTypes.Time);
            strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "StrandedCount"));
            strandedSeries.DataSource = historyPassengerFlow;
           // vcMonthStrandCount.Series.Add(accInSeries);
            //vcMonthStrandCount.Series.Add(accOutSeries);
            vcMonthStrandCount.Series.Add(strandedSeries);
        }

        private void SetMonthWorkingDayChart()
        {
            List<DayOfWeek> dayOfWeeks = new List<DayOfWeek>();
            DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1,0,0,0);
            DateTime endTime = time.AddMonths(1);

            dayOfWeeks.Add(DayOfWeek.Monday);
            dayOfWeeks.Add(DayOfWeek.Tuesday);
            dayOfWeeks.Add(DayOfWeek.Wednesday);
            dayOfWeeks.Add(DayOfWeek.Thursday);
            dayOfWeeks.Add(DayOfWeek.Friday);
            var workDaySource = m_ViewModel.GetHistoryPassengerByWeek(false, time, endTime, dayOfWeeks);

            Axis xAxis = new Axis();
            DateTime minDateTime = workDaySource.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = workDaySource.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            if (maxDateTime.Year == minDateTime.Year && maxDateTime.Month == minDateTime.Month &&
                maxDateTime.Day == minDateTime.Day)
            {
                xAxis.ValueFormatString = "HH:mm";
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 1;
            }
            else
            {
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 4;
            }
            vcMonthWorkDay.AxesX.Add(xAxis);

            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name + " 各通道";
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年" + time.Month + "月" + title1 + " 星期一至星期五 每日平均客流分时段分布图";
            vcMonthWorkDay.Titles.Add(vcChart1Title);

            var mondaySeries = GetWorkDayDataSeries(time, endTime, DayOfWeek.Monday);
            var tuesdaySeries = GetWorkDayDataSeries(time, endTime, DayOfWeek.Tuesday);
            var wedSeries = GetWorkDayDataSeries(time, endTime, DayOfWeek.Wednesday);
            var thursSeries = GetWorkDayDataSeries(time, endTime, DayOfWeek.Thursday);
            var fridaySeries = GetWorkDayDataSeries(time, endTime, DayOfWeek.Friday);

            vcMonthWorkDay.Series.Add(mondaySeries);
            vcMonthWorkDay.Series.Add(tuesdaySeries);
            vcMonthWorkDay.Series.Add(wedSeries);
            vcMonthWorkDay.Series.Add(thursSeries);
            vcMonthWorkDay.Series.Add(fridaySeries);
        }

        private void SetMonthHolidayChart()
        {
            List<DayOfWeek> dayOfWeeks = new List<DayOfWeek>();
            DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1, 0, 0, 0);
            DateTime endTime = time.AddMonths(1);

            dayOfWeeks.Add(DayOfWeek.Saturday);
            dayOfWeeks.Add(DayOfWeek.Sunday);
            var workDaySource = m_ViewModel.GetHistoryPassengerByWeek(false, time, endTime, dayOfWeeks);

            Axis xAxis = new Axis();
            DateTime minDateTime = workDaySource.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = workDaySource.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            if (maxDateTime.Year == minDateTime.Year && maxDateTime.Month == minDateTime.Month &&
                maxDateTime.Day == minDateTime.Day)
            {
                xAxis.ValueFormatString = "HH:mm";
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 1;
            }
            else
            {
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 4;
            }
            vcMonthHoliDay.AxesX.Add(xAxis);

            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name;
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年" + time.Month + "月" + title1 + " 星期六至星期日 每日平均客流分时段分布图";
            vcMonthHoliDay.Titles.Add(vcChart1Title);

            var mondaySeries = GetWorkDayDataSeries(time, endTime, DayOfWeek.Saturday);
            var tuesdaySeries = GetWorkDayDataSeries(time, endTime, DayOfWeek.Sunday);

            vcMonthHoliDay.Series.Add(mondaySeries);
            vcMonthHoliDay.Series.Add(tuesdaySeries);

        }

        private void SetMonthWorkHolidayCompareChart()
        {
            List<DayOfWeek> dayOfWeeks = new List<DayOfWeek>();
            DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1, 0, 0, 0);
            DateTime endTime = time.AddMonths(1);

            dayOfWeeks.Add(DayOfWeek.Saturday);
            dayOfWeeks.Add(DayOfWeek.Sunday);
            var holidaySource = m_ViewModel.GetHistoryPassengerByWeek(false, time, endTime, dayOfWeeks);

            dayOfWeeks.Add(DayOfWeek.Monday);
            dayOfWeeks.Add(DayOfWeek.Tuesday);
            dayOfWeeks.Add(DayOfWeek.Wednesday);
            dayOfWeeks.Add(DayOfWeek.Thursday);
            dayOfWeeks.Add(DayOfWeek.Friday);
            var workdaySource = m_ViewModel.GetHistoryPassengerByWeek(false, time, endTime, dayOfWeeks);

            Axis xAxis = new Axis();
            DateTime minDateTime = workdaySource.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = workdaySource.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            if (maxDateTime.Year == minDateTime.Year && maxDateTime.Month == minDateTime.Month &&
                maxDateTime.Day == minDateTime.Day)
            {
                xAxis.ValueFormatString = "HH:mm";
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 1;
            }
            else
            {
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 4;
            }
            vcMonthWorkHoliDay.AxesX.Add(xAxis);

            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name;
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年" + time.Month + "月" + title1 + " 平时，周末客流对比图（每半小时）";
            vcMonthWorkHoliDay.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "平时", ChartValueTypes.Time);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = workdaySource;

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Line, "周末", ChartValueTypes.Time);
            series2.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series2.DataSource = holidaySource;

            vcMonthWorkHoliDay.Series.Add(series);
            vcMonthWorkHoliDay.Series.Add(series2);
        }

        private void SetAllPassengerSexChart()
        {
            DateTime dateTime = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1, 0, 0, 0);

            //this month
            DateTime startTime = dateTime;
            DateTime endTime = dateTime.AddMonths(1);
            SetPassengerSexChart("本月男女客流占比图", startTime, endTime, vcThisMonthSex);

            //Last week
            startTime = dateTime.AddMonths(-1);
            endTime = dateTime;
            SetPassengerSexChart("上月男女客流占比图", startTime, endTime, vcLastMonthSex);

            //Last Year
            startTime = dateTime.AddYears(-1);
            endTime = dateTime.AddYears(-1).AddMonths(1);
            SetPassengerSexChart("去年同期", startTime, endTime, vcLastYearSex);

        }

        private void SetPassengerSexChart(string title, DateTime startTime, DateTime endTime, Chart vcChart)
        {
            List<HistoryPassengerFlow> sexHistoryPassengerFlows = m_ViewModel.GetPassengerflowsBySex(startTime, endTime);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = title;
            vcChart.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Pie, "客流", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "SexName"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.LabelText = "#AxisXLabel (#Percentage%)";
            series.DataSource = sexHistoryPassengerFlows;
            vcChart.Series.Add(series);
        }

        private void SetPassengerAgeChart()
        {
            DateTime dateTime = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1, 0, 0, 0);

            DateTime startTime = dateTime;
            DateTime endTime = dateTime.AddMonths(1);
            List<HistoryPassengerFlow> ageHistoryPassengerFlows = m_ViewModel.GetAgeDurationPassengerFlow(startTime, endTime);

            Axis xAxis = new Axis();
            xAxis.AxisMinimum = 0;
            xAxis.AxisMaximum = 120;

            xAxis.IntervalType = IntervalTypes.Number;
            xAxis.Interval = 5;

            vcMonthAgeChart.AxesX.Add(xAxis);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = "本月/上月各年龄段客流图";
            vcMonthAgeChart.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "本月", ChartValueTypes.Numeric);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "Age"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = ageHistoryPassengerFlows;
            vcMonthAgeChart.Series.Add(series);

            startTime = dateTime.AddMonths(-1);
            endTime = dateTime;
            List<HistoryPassengerFlow> ageHistoryPassengerFlows2 = m_ViewModel.GetAgeDurationPassengerFlow(startTime, endTime);

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Line, "上月", ChartValueTypes.Numeric);
            series2.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "Age"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series2.DataSource = ageHistoryPassengerFlows2;
            vcMonthAgeChart.Series.Add(series2);
        }

        private DataSeries GetWorkDayDataSeries(DateTime startTime, DateTime endTime, DayOfWeek dayOfWeek)
        {
            List<DayOfWeek> dayOfWeeks = new List<DayOfWeek>();
            dayOfWeeks.Add(dayOfWeek);
            var workDaySource = m_ViewModel.GetHistoryPassengerByWeek(false, startTime, endTime, dayOfWeeks);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, GetWeekDayString(dayOfWeek), ChartValueTypes.Time);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = workDaySource;

            return series;
        }

        private string GetWeekDayString(DayOfWeek dayOfWeek)
        {
            string weekDay = "星期一";
            switch (dayOfWeek)
            { 
                case DayOfWeek.Sunday:
                    weekDay = "星期日";
                    break;
                case DayOfWeek.Monday:
                    weekDay = "星期一";
                    break;
                case DayOfWeek.Tuesday:
                    weekDay = "星期二";
                    break;
                case DayOfWeek.Wednesday:
                    weekDay = "星期三";
                    break;
                case DayOfWeek.Thursday:
                    weekDay = "星期四";
                    break;
                case DayOfWeek.Friday:
                    weekDay = "星期五";
                    break;
                case DayOfWeek.Saturday:
                    weekDay = "星期六";
                    break;
            }

            return weekDay;
        }

        #endregion

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }
    }
}
